from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView

from rest_framework.response import Response

from .models import User


from rest_framework.generics import CreateAPIView



# 用户
class RegisterUsernameCountAPIView(APIView):
    # 查询用户个数
    def get(self,request,username):
        count=User.objects.filter(username=username).count()
        context={
            'count':count,
            'username':username
        }
        return Response(context)

#手机号
class RegisterPhoneCountAPIView(APIView):
    # 查询手机号的个数
    def get(self,request,mobile):

        #通过模型查询获取手机号的个数
        count=User.objects.filter(mobile=mobile).count()

        context={
            'count':count,
            'phone':mobile
        }
        return Response(context)


from .serializers import RegisterCreateSerializer
class RegisterCreateView(CreateAPIView):
    # 用户注册
    serializer_class = RegisterCreateSerializer


from rest_framework.generics import RetrieveAPIView

from rest_framework.permissions import IsAuthenticated

from .serializers import UserCenterInfoSerializer



class UserDetailView(RetrieveAPIView):
    #获取登录用户的信息
    permission_classes = [IsAuthenticated]

    serializer_class = UserCenterInfoSerializer

    def get_object(self):
        return self.request.user




from rest_framework.generics import UpdateAPIView
from .serializers import UserEmailSerializer

class EmailView(UpdateAPIView):
    # 保存邮箱
    permission_classes = [IsAuthenticated]


    def get_object(self):

        return self.request.user
    serializer_class = UserEmailSerializer

from rest_framework import status
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import BadSignature,SignatureExpired
# 不是错误
from mall import settings

class UserEmailVerificationAPIView(APIView):

    def get(self,request):
        # 接收token
        token=request.query_params.get('token')
        if token is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 对token解密
        # TODO s=Serializer(secret_key=settings.SECRET_KEY,expires_in=3600)
        # SECRET_KEY = 'c*xu*gd8hdpa$8m2u#kcu3y(_e-i&ea#&m^6@7z-fys1e!y1!m'

        s=Serializer(secret_key=settings.SECRET_KEY,expires_in=3600)
        # 解密过程
        try:
            result=s.loads(token)

        except BadSignature:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 查询用户信息
        id=result.get('user_id')
        email=result.get('email')

        try:
            user=User.objects.get(id=id,email=email)
        except User.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 更改用户信息
        user.email_active=True
        user.save()
        # 返回响应
        return Response({'msg':'ok'})

